<?php

namespace app\api\controller;

use think\facade\Request;
use app\common\Common;
use app\api\service\TiktokService;
use app\common\Error;

class Tiktok extends Base
{
    private $service;

    public function __construct(TiktokService $service)
    {
        $this->service = $service;
    }

    // 抖音登录
    public function login()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Tiktok::class)->scene('login')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $data = $this->service->tiktokUserLogin($params);

        if (empty($data) || !empty($data['message'])) {
            $message = !empty($data['message']) ? $data['message'] : Error::FAIL_AUTHORIZED_lOGIN;
            return Common::fail($message);
        }

        return Common::success($data);
    }

    // 预支付下单
    public function placeOrder()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Tiktok::class)->scene('place_order')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $data = $this->service->advancePaymentOrder($params, $this->getUserID());
        if (empty($data) || !empty($data['message'])) {
            $message = !empty($data['message']) ? $data['message'] : Error::FAIL_AUTHORIZED_lOGIN;
            return Common::fail($message);
        }

        return Common::success($data);
    }

    // 回调（用于接收抖音异步通知消息，需要传入 https 公网可访问的网页地址）
    public function callback()
    {
        $params = Request::param();
        // $postStr = '{"msg":"{\"appid\":\"tt716807d5ee55bba601\",\"cp_orderno\":\"202311161735503915\",\"cp_extra\":\"\",\"way\":\"2\",\"channel_no\":\"2023111622001494561411475412\",\"channel_gateway_no\":\"\",\"payment_order_no\":\"DPS2311161735519030294838136145\",\"out_channel_order_no\":\"2023111622001494561411475412\",\"total_amount\":1,\"status\":\"SUCCESS\",\"seller_uid\":\"72726402782578957340\",\"extra\":\"\",\"item_id\":\"\",\"paid_at\":1700127366,\"message\":\"\",\"order_id\":\"N7301991351732865306\",\"ec_pay_trade_no\":\"DTPP2311161735519030293691256145\"}","msg_signature":"b6afcb7ebabb14b59b254f46c98810f8e44cdc32","nonce":"76","timestamp":"1700127366","type":"payment"}';
        // $params = json_decode($postStr, true);

        $data = $this->service->payCallBack($params);
        echo json_encode($data);
        exit();
    }

    //新支付回调
    public function newCallback()
    {
        $params = Request::param();
        flog([
            'params' => $params
        ], 'dy_new_pay_callback');
        $data = $this->service->newPayCallBack($params);
        echo json_encode($data);
        exit();
    }
}
